package me.info.sboot.app.test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * form https://blog.csdn.net/weixin_42388901/article/details/105941302
 *
 * @author Amber
 * @version v0.0.1
 * @date 2020/12/22 9:58
 */
@SpringBootTest
public class EsClientTest1 {

  @Autowired RestHighLevelClient rhlClient;

  private static String index = "im.robot";

  @Test
  public void create_index_test() throws IOException {
    // 创建索引请求
    CreateIndexRequest request = new CreateIndexRequest(index);

    // 配置settings
    request.settings(
        Settings.builder().put("index.number_of_shards", 1).put("index.number_of_replicas", 1));

    // 配置mapping, keywords, question, hits
    XContentBuilder mapping =
        JsonXContent.contentBuilder()
            .startObject()
            .startObject("properties")
            .startObject("keywords")
            .field("type", "text")
            .startObject("fields")
            .startObject("title_ik_smart")
            .field("type", "text")
            .field("analyzer", "ik_smart")
            .endObject()
            .startObject("title_ik_max_word")
            .field("type", "text")
            .field("analyzer", "ik_max_word")
            .endObject()
            .endObject()
            .endObject()
            // field question
            .startObject("question")
            .field("type", "text")
            .startObject("fields")
            .startObject("keyword")
            .field("type", "keyword")
            .endObject()
            .endObject()
            .endObject()
            // field hits
            .startObject("hits")
            .field("type", "long")
            .endObject()
            .endObject()
            .endObject();
    request.mapping(mapping);
    rhlClient.indices().create(request, RequestOptions.DEFAULT);
  }

  @Test
  public void test_analyze() throws Exception {

    List<String> rv = getAnalyze("使用关键词匹配做智能客服机器人的时候，后台需要输入一些问题，并且提供一些关键词供运营去选择");
    rv.stream().forEach(System.out::println);
  }

  public List<String> getAnalyze(String text) throws Exception {
    List<String> list = new ArrayList<String>();
    Request request = new Request("GET", "_analyze");
    JSONObject entity = new JSONObject();
    entity.put("analyzer", "ik_max_word");
    // entity.put("analyzer", "ik_smart");
    entity.put("text", text);
    request.setJsonEntity(entity.toJSONString());
    Response response = rhlClient.getLowLevelClient().performRequest(request);
    JSONObject tokens = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
    JSONArray arrays = tokens.getJSONArray("tokens");
    for (int i = 0; i < arrays.size(); i++) {
      JSONObject obj = JSON.parseObject(arrays.getString(i));
      list.add(obj.getString("token"));
    }
    return list;
  }

  @Test
  public  void  test_search() throws IOException {
    // 从es中根据关键词匹配算分返回结果，如果算分相同按照hits字段排序
    String question="匹配";
    SearchRequest request = new SearchRequest(index);
    SearchSourceBuilder searchSource = new SearchSourceBuilder()
        .query(QueryBuilders.matchQuery("keywords", question))
        .sort("_score", SortOrder.DESC)
        .sort("hits", SortOrder.DESC)
        .size(5);

    request.source(searchSource);

    SearchResponse response = rhlClient.search(request, RequestOptions.DEFAULT);
    SearchHit[] hits = response.getHits().getHits();

    List<String> list = new ArrayList<>();
    for (SearchHit hit : hits) {
      JSONObject jsonObject = JSONObject.parseObject(hit.getSourceAsString());
      Object questionVal = jsonObject.get("question");
      String questionStr = questionVal == null ? "" : questionVal.toString();

      Object keywordsVal = jsonObject.get("keywords");
      String keywordsStr = keywordsVal == null ? "" : keywordsVal.toString();
      list.add(questionStr);
    }
  }
}
